package com.ideaction.game.sec;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.ideaction.game.config.prop.NolimitUrlConfigProperties;
import com.ideaction.game.exception.AuthFailException;
import com.ideaction.game.globalconst.SystemNotice;
import com.ideaction.game.utils.IpUtils;
import com.ideaction.game.utils.Localization;
import com.ideaction.game.utils.TokenUtil;

import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.slf4j.Slf4j;

/**
 * 权限拦截
 * 
 * @author ZGame
 *
 *
 */
@Component
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {
	@Autowired
	RedissonClient redissonClient;
	@Value("${security.open}")
	private boolean openSecurity;// token和加解密
	@Value("${limiter.open}")
	private boolean openLimiter;// 限流器
	@Autowired
	private NolimitUrlConfigProperties nolimitUrl;//不需要token验证的urls
	
	// @Autowired
	// private RedissionUserLimiter redissionUserLimiter;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String token = request.getHeader("AccessToken");
		String uid = request.getHeader("Uid");
		/*
		 * if (openLimiter) { RRateLimiter limiter =
		 * redissionUserLimiter.getUserLimiter(uid); if (limiter.tryAcquire()) {
		 * // 超过了限定访问频率,有可能是不正常访问 } }
		 */
		String clientIp = IpUtils.getClientIp(request);
		String url = request.getRequestURL().toString();

		int index = url.lastIndexOf("?");
		if (index < 0) {
			index = url.length();
		}
		//login拦截特殊处理
		String action = url.substring(url.lastIndexOf("/") + 1, index);
		
		log.info("action:"+action+" uid:"+uid+" token:"+token);
		
		if (action.equalsIgnoreCase("Login")) {
			String access_token = TokenUtil.upToken(redissonClient, uid, clientIp);
			response.setHeader("AccessToken", access_token);
			return true;
		}
		//不需要token,直接放行
		List<String> nolimitUrls = nolimitUrl.getNolimitUrls();
		if(nolimitUrls.contains(action)){
			return true;
		}
		if(StringUtils.isBlank(uid)||StringUtils.isBlank(token)||!TokenUtil.auth(redissonClient, token, clientIp, uid)){
			throw new AuthFailException(Localization.getInstance().get(SystemNotice.TOKEN_VERIFY_FAIL, null), uid);
		}
		return true;
	}
}
